/*
 * @Description: 描述信息
 * @Version: 版本号
 * @Author: xuebao
 * @Date: 2023-12-08 15:21:34
 * @LastEditors: renmengxue
 * @LastEditTime: 2023-12-08 16:54:07
 */
import { defineStore } from 'pinia'
import axios from 'axios'
import { ResponseType, ImageProps, ListDictType, ListResType, ListReqType } from './utils'

import { arrToObj, objToArr } from '../helper'

export interface ColumnProps {
  _id:string,
  title:string,
  avatar?:string,
  description:string,
}

export interface GlobalColumnProps {
  data:ListDictType<ColumnProps>,
  currentPage:number,
  total:number
}
export const useColumnStore = defineStore('column', {
  state: ():GlobalColumnProps => {
    return {
      data: {},
      currentPage: 0,
      total: 0
    }
  },
  actions: {
   async fetchColumns(params: ListReqType = {}) {
    const { currentPage = 1, pageSize = 6 } = params
    if (this.currentPage < currentPage) {
      // 才请求
      const { data } = await axios.get<ListResType<ColumnProps>>(`/columns?currentPage=${currentPage}&pageSize=${pageSize}`)
      const { count, list } = data.data
      this.$patch({
        currentPage,
        data: { ...this.data, ...arrToObj(list) },
        total: count
      })
    }
    },
    async fetchColumn(id:string) {
      const IdArr = Object.keys(this.data)
      if (!IdArr.includes(id)) {
        const { data: rawData } = await axios.get<ResponseType<ColumnProps>>(`/columns/${id}`)
        const { data } = rawData// 重命名
        this.data[data._id] = data
      }
    }
  },
  getters: {
    getColumns: (state:any) => {
      return objToArr(state.data)
    },
    getColumnsById: (state) => (id:string) => {
      return state.data[id]
    }
  }
})
